package com.tengniu.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.tengniu.api.common.CurrentUser;
import com.tengniu.biz.bo.LoginResultBO;
import com.tengniu.common.core.domain.model.LoginUser;
import com.tengniu.common.utils.SecurityUtils;
import com.tengniu.common.utils.StringUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

@Component
public class AuditMetaObjectHandler implements MetaObjectHandler {

    private static final String CREATE_BY = "createBy";
    private static final String UPDATE_BY = "updateBy";
    private static final String CREATE_TIME = "createTime";
    private static final String UPDATE_TIME = "updateTime";

    @Override
    public void insertFill(MetaObject metaObject) {
        Date now = new Date();
        if (metaObject.hasSetter(CREATE_TIME)) {
            setFieldValByName(CREATE_TIME, now, metaObject);
        }
        if (metaObject.hasSetter(UPDATE_TIME)) {
            setFieldValByName(UPDATE_TIME, now, metaObject);
        }
        LoginUser sysUser = SecurityUtils.getLoginUser();
        String username = Objects.nonNull(sysUser)?sysUser.getUsername():"system";
        if (StringUtils.isBlank(username)) {
            LoginResultBO appLoginUser = CurrentUser.getCurrentUser();
            username = Objects.nonNull(appLoginUser)?appLoginUser.getCompanyName():"system";
        }
        if (metaObject.hasSetter(CREATE_BY)) {
            setFieldValByName(CREATE_BY, username, metaObject);
        }
        if (metaObject.hasSetter(UPDATE_BY)) {
            this.setFieldValByName(UPDATE_BY, username, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasSetter(UPDATE_TIME)) {
            this.setFieldValByName(UPDATE_TIME, new Date(), metaObject);
        }
        if (metaObject.hasSetter(UPDATE_BY)) {
            LoginUser sysUser = SecurityUtils.getLoginUser();
            String username = Objects.nonNull(sysUser)?sysUser.getUsername():"";
            if (StringUtils.isBlank(username)) {
                LoginResultBO appLoginUser = CurrentUser.getCurrentUser();
                username = Objects.nonNull(appLoginUser)?appLoginUser.getCompanyName():"system";
            }
            this.setFieldValByName(UPDATE_BY, username, metaObject);
        }
    }
}
